import React, { useState, useEffect } from 'react';
import {
  Card,
  Table,
  Button,
  Space,
  Modal,
  Form,
  Input,
  Select,
  message,
  DatePicker,
  InputNumber,
  Tag,
  Switch,
  Popover,
  ConfigProvider,
} from 'antd';
import {
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
} from '@ant-design/icons';
import { getAnnouncementPage, addAnnouncement, updateAnnouncement, deleteAnnouncement, AnnouncementInfo } from '@/services/AnnouncementService';
import { famousPersonId } from '@/services';
import dayjs from 'dayjs';
import styles from './index.less';
import zhCN from 'antd/locale/zh_CN';

const { RangePicker } = DatePicker;

const AnnouncementAdmin: React.FC = () => {
  const [form] = Form.useForm();
  const [data, setData] = useState<AnnouncementInfo[]>([]);
  const [loading, setLoading] = useState(false);
  const [modalVisible, setModalVisible] = useState(false);
  const [editingId, setEditingId] = useState<number>();
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 20,
    total: 0,
  });
  const [searchForm] = Form.useForm();

  // 加载数据
  const loadData = async (page = pagination.current, pageSize = pagination.pageSize) => {
    try {
      setLoading(true);
      const values = await searchForm.validateFields();
      const response = await getAnnouncementPage({
        pageCurrent: page,
        pageSize: pageSize,
        famousPersonId: famousPersonId,
        keyword: values.keyword,
        type: values.type,
        status: values.status,
      });
      setData(response.list);
      setPagination({
        current: page,
        pageSize: pageSize,
        total: response.totalCount,
      });
    } catch (error) {
      message.error('获取数据失败');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    loadData();
  }, []);

  // 处理表单提交
  const handleSubmit = async (values: any) => {
    try {
      const submitData = {
        ...values,
        famousPersonId,
        startTime: values.time?.[0]?.format('YYYY-MM-DD HH:mm:ss'),
        endTime: values.time?.[1]?.format('YYYY-MM-DD HH:mm:ss'),
        isTop: values.isTop ? 1 : 0,
      };

      if (editingId) {
        await updateAnnouncement({ ...submitData, id: editingId });
        message.success('更新成功');
      } else {
        await addAnnouncement(submitData);
        message.success('添加成功');
      }
      setModalVisible(false);
      loadData();
    } catch (error) {
      message.error('操作失败');
    }
  };

  // 处理删除
  const handleDelete = async (id: number) => {
    Modal.confirm({
      title: '确认删除',
      content: '确定要删除这条公告吗？',
      okText: '确定',
      cancelText: '取消',
      onOk: async () => {
        try {
          await deleteAnnouncement([id]);
          message.success('删除成功');
          loadData();
        } catch (error) {
          message.error('删除失败');
        }
      },
    });
  };

  // 处理编辑
  const handleEdit = (record: AnnouncementInfo) => {
    setEditingId(record.id);
    form.setFieldsValue({
      ...record,
      time: record.startTime && record.endTime ? [
        dayjs(record.startTime),
        dayjs(record.endTime),
      ] : undefined,
      isTop: record.isTop === 1,
    });
    setModalVisible(true);
  };

  const columns = [
    {
      title: '标题',
      dataIndex: 'title',
      key: 'title',
      width: '10%',
    },
    {
      title: '内容',
      dataIndex: 'content',
      key: 'content',
      width: '25%',
      ellipsis: true,
      render: (content: string) => (
        <Popover 
          content={<div style={{ maxWidth: 400, whiteSpace: 'pre-wrap' }}>{content}</div>}
          title="公告内容"
          placement="topLeft"
          overlayStyle={{ maxWidth: '50vw' }}
        >
          <span>{content}</span>
        </Popover>
      ),
    },
    {
      title: '类型',
      dataIndex: 'type',
      key: 'type',
      width: '10%',
      render: (type: number) => {
        const typeMap = {
          1: { text: '普通公告', color: 'default' },
          2: { text: '重要公告', color: 'warning' },
          3: { text: '紧急公告', color: 'error' },
        };
        return <Tag color={typeMap[type as keyof typeof typeMap].color}>{typeMap[type as keyof typeof typeMap].text}</Tag>;
      },
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: '12%',
      render: (status: number) => (
        <Tag color={status === 1 ? 'success' : 'default'}>
          {status === 1 ? '已发布' : '未发布'}
        </Tag>
      ),
    },
    {
      title: '置顶',
      dataIndex: 'isTop',
      key: 'isTop',
      width: '10%',
      render: (isTop: number) => (
        <Tag color={isTop === 1 ? 'processing' : 'default'}>
          {isTop === 1 ? '是' : '否'}
        </Tag>
      ),
    },
    {
      title: '有效期',
      key: 'time',
      width: '20%',
      render: (_: any, record: AnnouncementInfo) => {
        if (!record.startTime && !record.endTime) return '-';
        return `${record.startTime || ''} ~ ${record.endTime || ''}`;
      },
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record: AnnouncementInfo) => (
        <Space>
          <Button
            type="link"
            icon={<EditOutlined />}
            onClick={() => handleEdit(record)}
          >
            编辑
          </Button>
          <Button
            type="link"
            danger
            icon={<DeleteOutlined />}
            onClick={() => handleDelete(record.id!)}
          >
            删除
          </Button>
        </Space>
      ),
    },
  ];

  // 添加搜索表单渲染函数
  const renderSearchForm = () => (
    <div className={styles.toolbarContent}>
      <Form
        form={searchForm}
        layout="inline"
        onFinish={() => loadData(1)}
      >
        <Form.Item name="keyword">
          <Input 
            placeholder="请输入公告标题" 
            allowClear 
            style={{ width: 200 }}
          />
        </Form.Item>
        <Form.Item name="type">
          <Select
            placeholder="公告类型"
            allowClear
            style={{ width: 120 }}
          >
            <Select.Option value={1}>普通公告</Select.Option>
            <Select.Option value={2}>重要公告</Select.Option>
            <Select.Option value={3}>紧急公告</Select.Option>
          </Select>
        </Form.Item>
        <Form.Item name="status">
          <Select
            placeholder="发布状态"
            allowClear
            style={{ width: 120 }}
          >
            <Select.Option value={0}>未发布</Select.Option>
            <Select.Option value={1}>已发布</Select.Option>
          </Select>
        </Form.Item>
        <Form.Item>
          <Space>
            <Button type="primary" htmlType="submit">
              搜索
            </Button>
            <Button onClick={() => {
              searchForm.resetFields();
              loadData(1, 20);
            }}>
              重置
            </Button>
          </Space>
        </Form.Item>
      </Form>
      <Button
        type="primary"
        icon={<PlusOutlined />}
        onClick={() => {
          setEditingId(undefined);
          form.resetFields();
          setModalVisible(true);
        }}
      >
        新增公告
      </Button>
    </div>
  );

  // 处理表格变化
  const handleTableChange = (newPagination: any) => {
    loadData(newPagination.current, newPagination.pageSize);
  };

  return (
    <ConfigProvider locale={zhCN}>
      <Card title="公告管理">
        <div className={styles.toolbar}>
          {renderSearchForm()}
        </div>
        <Table
          columns={columns}
          dataSource={data}
          rowKey="id"
          loading={loading}
          scroll={{ y: 'calc(100vh - 410px)', scrollToFirstRowOnChange: false }}
          pagination={{
            ...pagination,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total) => `共 ${total} 条`,
            pageSizeOptions: [ '20', '50', '100'],
          }}
          onChange={handleTableChange}
        />

        <Modal
          title={editingId ? '编辑公告' : '新增公告'}
          open={modalVisible}
          onCancel={() => setModalVisible(false)}
          footer={null}
          width={800}
        >
          <Form
            form={form}
            layout="vertical"
            onFinish={handleSubmit}
          >
            <Form.Item
              name="title"
              label="公告标题"
              rules={[{ required: true, message: '请输入公告标题' }]}
            >
              <Input placeholder="请输入公告标题" />
            </Form.Item>

            <Form.Item
              name="content"
              label="公告内容"
              rules={[{ required: true, message: '请输入公告内容' }]}
            >
              <Input.TextArea rows={4} placeholder="请输入公告内容" />
            </Form.Item>

            <Form.Item
              name="type"
              label="公告类型"
              rules={[{ required: true, message: '请选择公告类型' }]}
            >
              <Select>
                <Select.Option value={1}>普通公告</Select.Option>
                <Select.Option value={2}>重要公告</Select.Option>
                <Select.Option value={3}>紧急公告</Select.Option>
              </Select>
            </Form.Item>

            <Form.Item
              name="status"
              label="发布状态"
              rules={[{ required: true, message: '请选择发布状态' }]}
            >
              <Select>
                <Select.Option value={0}>未发布</Select.Option>
                <Select.Option value={1}>发布</Select.Option>
              </Select>
            </Form.Item>

            <Form.Item
              name="priority"
              label="优先级"
              initialValue={0}
            >
              <InputNumber 
                min={0} 
                max={99} 
                style={{ width: '100%' }} 
                placeholder="数字越大优先级越高(选填)" 
              />
            </Form.Item>

            <Form.Item
              name="time"
              label="有效期"
            >
              <RangePicker
                showTime
                style={{ width: '100%' }}
                placeholder={['开始时间', '结束时间']}
              />
            </Form.Item>

            <Form.Item
              name="isTop"
              label="置顶"
              valuePropName="checked"
            >
              <Switch />
            </Form.Item>

            <Form.Item className={styles.modalFooter}>
              <Space>
                <Button onClick={() => setModalVisible(false)}>取消</Button>
                <Button type="primary" htmlType="submit">
                  保存
                </Button>
              </Space>
            </Form.Item>
          </Form>
        </Modal>
      </Card>
    </ConfigProvider>
  );
};

export default AnnouncementAdmin; 